package m.common.model.config;

import m.common.model.*;
import m.system.listener.InitListener;
import m.system.util.AnnotationUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ModelConfig {
	private static boolean init=false;
	private static void doInit(){
		if(init) return;
		init=true;
		try {
			InitListener.initDB(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static String tableSchema;
	private static final List<Class<? extends Model>> tableList=new ArrayList<>();
	private static final Map<Class<? extends Model>,TableMeta> tableMap=new HashMap<>();
	private static final Map<Class<? extends Model>,Map<String,FieldMeta>> fieldMetaMap=new HashMap<>();
	private static final Map<Class<? extends Model>,Map<String,LinkTableMeta>> linkTableMetaMap=new HashMap<>();
	private static final Map<Class<? extends Model>,Map<String, QueryFieldMeta>> queryFieldMetaMap=new HashMap<>();
	//set
	public static void setTableSchema(String tableSchema) {
		ModelConfig.tableSchema = tableSchema;
	}
	public static <T extends Model> void fillModelInfo(Class<T> clazz,TableMeta tableMeta,
			Map<String,FieldMeta> fieldMap,Map<String,LinkTableMeta> linkTableMap,Map<String,QueryFieldMeta> queryFieldMap){
		tableList.add(clazz);
		tableMap.put(clazz, tableMeta);
		fieldMetaMap.put(clazz, fieldMap);
		linkTableMetaMap.put(clazz, linkTableMap);
		queryFieldMetaMap.put(clazz, queryFieldMap);
		init=true;
	}
	//get
	public static <T extends Model> TableMeta getTableMeta(Class<T> clazz){
		doInit();
        return tableMap.get(clazz);
	}
	public static <T extends Model> Map<String,FieldMeta> getFieldMetaMap(Class<T> clazz){
		doInit();
        Map<String, FieldMeta> tmp = fieldMetaMap.get(clazz);
        if(null!=tmp) return tmp;
        tmp=AnnotationUtil.getAnnotationMap4Field(FieldMeta.class, clazz);
        return tmp;
    }
	public static <T extends Model> Map<String,LinkTableMeta> getLinkTableMetaMap(Class<T> clazz){
		doInit();
        Map<String, LinkTableMeta> tmp = linkTableMetaMap.get(clazz);
        if(null!=tmp) return tmp;
        tmp=AnnotationUtil.getAnnotationMap4Field(LinkTableMeta.class, clazz);
        return tmp;
    }
	public static <T extends Model> Map<String, QueryFieldMeta> getQueryFieldMetaMap(Class<T> clazz){
		doInit();
        Map<String, QueryFieldMeta> tmp = queryFieldMetaMap.get(clazz);
        if(null!=tmp) return tmp;
        tmp=AnnotationUtil.getAnnotationMap4Field(QueryFieldMeta.class, clazz);
        return tmp;
    }
 	public static String getTableSchema() {
		return tableSchema;
	}
	public static List<Class<? extends Model>> getTableList() {
		doInit();
		return tableList;
	}
}
